//
//  ReadBookViewController.swift
//  BLH
//
//  Created by zhangshumeng on 2021/8/9.
//

import UIKit

class ReadBookViewController: BaseViewController {

    private let bookModel: BookModel
    private var playerIndex: Int = 0
    
    private lazy var topView: PlayerTopView = {
        let view = PlayerTopView()
        view.lockBtn.isHidden = true
        view.forScreenBtn.isHidden = true
        view.didClose = { [weak self] in
            guard let `self` = self else { return }
            self.goBack()
        }
        return view
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = UIScreen.main.bounds.size
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.backgroundColor = .black
        view.delegate = self
        view.dataSource = self
        view.register(ReadBookCell.self)
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.isPagingEnabled = true
        return view
    }()
    
    private lazy var player: AudioPlayer = {
        let player = AudioPlayer()
        player.delegate = self
        player.playbackPausesWhenResigningActive = false
        player.playbackPausesWhenBackgrounded = false
        player.playbackResumesWhenBecameActive = false
        player.playbackResumesWhenEnteringForeground = false
        return player
    }()
    
    init(bookModel: BookModel) {
        self.bookModel = bookModel
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationMask = .landscapeRight
        }
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationMask = .portrait
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        addSubviews()
        playerURL()
    }
    
    private func setupNav() {
        navigation.bar.isHidden = true
    }

    private func addSubviews() {
        view.addSubview(collectionView)
        view.addSubview(topView)
        
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        topView.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(50.fit)
        }
    }

    private func playerURL() {
        if playerIndex < 0 || playerIndex > bookModel.pagesv2.count - 1 {
            return
        }
        let model = bookModel.pagesv2[playerIndex]
        
        player.player(URL(fileURLWithPath: model.audioURL).absoluteString)
    }
}

extension ReadBookViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return bookModel.pagesv2.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: ReadBookCell.self, for: indexPath)
        cell.imgView.image = UIImage(contentsOfFile: bookModel.pagesv2[indexPath.item].imageURL)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        topView.isShow = !topView.isShow
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        debugPrint(scrollView.contentOffset.x)
        let offsetX = collectionView.contentOffset.x
        let currentIndex = Int(offsetX / UIScreen.width)
        if (currentIndex != playerIndex) {
            playerIndex = currentIndex
            playerURL()
        }
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        debugPrint(scrollView.contentOffset.x)
        let offsetX = collectionView.contentOffset.x
        let currentIndex = Int(offsetX / UIScreen.width)
        if (currentIndex != playerIndex) {
            playerIndex = currentIndex
            playerURL()
        }
    }
}

extension ReadBookViewController: AudioPlayerDelegate {
    
    func playerStateDidChange(_ player: AudioPlayer) {
        
    }
    
    func playerCurrentTimeDidChange(_ player: AudioPlayer) {
        
    }
    
    func playerPlaybackDidEnd(_ player: AudioPlayer) {
        if playerIndex < 0 || playerIndex + 1 >= bookModel.pagesv2.count - 1 {
            return
        }
        let offsetX = UIScreen.width * CGFloat(playerIndex + 1)
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
    }
    
    func player(_ player: AudioPlayer, didFailWithError error: Error?) {
        
    }
}
